<template>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px;margin-top: 330px;margin-left: 670px;"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    
    >
      <el-form-item label="用户名" prop="UserName" >
        <el-input v-model="ruleForm.UserName"  style="width:280px"/>
        <!-- style="width:200px" -->
      </el-form-item>


      <el-form-item label="密码" prop="Pwd">
        <el-input v-model="ruleForm.Pwd" type="password" show-password style="width:280px;" />
        <!-- style="width:200px;margin-left: 13px;" -->
      </el-form-item>


      <el-form-item label="验证码">
        <el-input v-model="ruleForm.vcode" style="width: 150px;" />
        <div class="captcha" @click="refreshCaptcha">
          <canvas ref="canvas" :width="width" :height="height"></canvas>
        </div>
      </el-form-item>
<!-- 
      <el-form-item label="验证码" >
        <div class="slider-captcha">

    <div class="captcha-image">
      <img :src="captchaImage" alt="Captcha Image"  />
      <div
        class="slider"
        :style="{ left: sliderLeft + 'px' }"
        @mousedown="startDrag"
      ></div>
    </div> -

     <div class="slider-track">

      <div
        class="target-marker"
        :style="{ left: targetPosition + 'px' }"
      ></div> 
      <div
        class="slider-thumb"
        :style="{ left: sliderLeft + 'px' }"
        @mousedown="startDrag"
      >
    </div>
    </div> 
    <p v-if="message"  :class="{ success: isSuccess, error: !isSuccess }">
      {{ message }}
    </p>
  </div>
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted,reactive} from 'vue';
  import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
  import axios from 'axios'
  import {useRouter,useRoute} from 'vue-router'
import {useCounterStore} from '@/stores/counter'

// 验证码图片
const captchaImage = ref('https://img2.baidu.com/it/u=3952060275,2571246916&fm=253&fmt=auto&app=120&f=JPEG?w=1422&h=800');
// 滑块的目标位置（随机生成）
const targetPosition = ref(Math.floor(Math.random() * 250)); // 0 - 250px
// 滑块的当前位置
const sliderLeft = ref(0);
// 是否正在拖动
const isDragging = ref(false);
// 提示信息
const message = ref('');
// // 是否验证成功
// const isSuccess = ref(false);

// 开始拖动
const startDrag = (event) => {
  isDragging.value = true;
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
};

// 拖动中
const onDrag = (event) => {
  if (isDragging.value) {
    const sliderTrack = document.querySelector('.slider-track');
    const rect = sliderTrack.getBoundingClientRect();
    let newLeft = event.clientX - rect.left - 10; // 10 是滑块宽度的一半
    newLeft = Math.max(0, Math.min(newLeft, rect.width - 20)); // 限制滑块范围
    sliderLeft.value = newLeft;
  }
};

// 停止拖动
const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);

  // 验证滑块位置
  if (Math.abs(sliderLeft.value - targetPosition.value) < 10) {
    message.value = '验证成功！';
    ruleForm.vcode = "101";
  } else {
    message.value = '验证失败，请重试！';
    ruleForm.vcode = '102';
  }
};

// 初始化
onMounted(() => {
  message.value = '请拖动滑块完成验证';
});

// 初始化
onMounted(() => {
  message.value = '请拖动滑块完成验证';
});
  interface RuleForm {
    UserName: string
    Pwd: string
    vcode:string
    scode:string
   
  }




  
let router=useRouter();
let Store=useCounterStore();

  const formSize = ref<ComponentSize>('default')
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive<RuleForm>({
    UserName: '',
    Pwd: '',
    vcode:'',
    scode:''
  })
  
  const locationOptions = ['Home', 'Company', 'School']
  
  const rules = reactive<FormRules<RuleForm>>({
    UserName: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    Pwd: [
      { required: true, message: '请输入密码', trigger: 'blur' },
    ],
  })
  
  const submitForm = async (formEl: FormInstance | undefined) => {

if (ruleForm.vcode.toLocaleLowerCase()!= captchaText.value.toLocaleLowerCase()) {
    console.log(captchaText.value)
    ElMessage.error("验证码不匹配");
    return;
  }

    // if(sliderLeft.value==0){
    //   ElMessage.error("请验证");
    //   return;
    // }
    if(ruleForm.vcode=="102"){
      ElMessage.error("验证失败");
      return;
    }
    else{
      ElMessage.success("验证成功")
      if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        axios({
          url:'http://localhost:5284/api/Users/LoginUser',
          method:'get',
          params:ruleForm
        })
        .then(res=>{
          if(res.data.code==101){
            console.log(res.data.data.userId)
            Store.CurrLoginUser.userId=res.data.data[0].userId;
            Store.CurrLoginUser.UserName=res.data.data[0].userName;
            Store.CurrLoginUser.roleid=res.data.data[0].roleId;
            Store.CurrLoginUser.roleName=res.data.data[0].roleName; 
            Store.CurrLoginUser.depenmentId=res.data.data[0].depenmentId; 
            Store.CurrLoginUser.levelId=res.data.data[0].levelId; 
            console.log(Store.CurrLoginUser.userId)
            console.log(Store.CurrLoginUser.UserName)
            ElMessage.success("登陆成功")
            router.push("/MainView")
          }
          else{
            ElMessage.error("用户名或密码错误")
          }
        })
      } else {
        console.log('error submit!', fields)
      }
    })
    }
   
  }
  
// 定义组件接收的属性
const props = defineProps({
  width: {
    type: Number,
    default: 120
  },
  height: {
    type: Number,
    default: 40
  },
  length: {
    type: Number,
    default: 4
  }
});

// 获取 canvas 元素的引用
const canvas = ref(null);
// 存储当前验证码文本
const captchaText = ref('');

// 生成随机验证码字符串
const generateCaptcha = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let text = '';
  for (let i = 0; i < props.length; i++) {
    text += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  captchaText.value = text;
  return text;
};

// 生成随机颜色
const getRandomColor = () => {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r},${g},${b})`;
};

// 绘制验证码到 canvas 上
const drawCaptcha = () => {
  const ctx = canvas.value.getContext('2d');
  // 清空画布
  ctx.clearRect(0, 0, props.width, props.height);
  // 设置字体和颜色
  ctx.font = '30px Arial';
  ctx.fillStyle = getRandomColor();

  const captcha = generateCaptcha();
  for (let i = 0; i < captcha.length; i++) {
    const x = (props.width / (props.length + 1)) * (i + 1);
    const y = props.height / 2 + Math.random() * 10 - 5;
    // 保存当前绘图状态
    ctx.save();
    // 平移和旋转文本
    ctx.translate(x, y);
    ctx.rotate((Math.random() - 0.5) * (Math.PI / 4));
    // 绘制单个字符
    ctx.fillText(captcha[i], 0, 0);
    // 恢复之前保存的绘图状态
    ctx.restore();
  }

  // 绘制干扰线
  for (let i = 0; i < 5; i++) {
    ctx.beginPath();
    ctx.strokeStyle = getRandomColor();
    ctx.moveTo(Math.random() * props.width, Math.random() * props.height);
    ctx.lineTo(Math.random() * props.width, Math.random() * props.height);
    ctx.stroke();
  }
};

// 刷新验证码
const refreshCaptcha = () => {
  drawCaptcha();
};

// 组件挂载后绘制验证码
onMounted(() => {
  drawCaptcha();
});

// 向外暴露获取验证码文本的方法
const getCaptchaText = () => {
  return captchaText.value;
};

defineExpose({
  getCaptchaText
});




  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  
  const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
  }))

</script>
<style scoped>
.slider-captcha {
text-align: center;
margin: 20px;
}

.captcha-image {
position: relative;
width: 300px;
height: 150px;
margin: 0 auto;
border: 1px solid #ccc;
}

.captcha-image img {
width: 100%;
height: 100%;
}

.slider {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 100%;
background-color: rgba(255, 0, 0, 0.5);
cursor: pointer;
}

.slider-track {
width: 300px;
height: 10px;
background-color: #f0f0f0;
margin: 10px auto;
position: relative;
border-radius: 5px;
}

.slider-thumb {
position: absolute;
top: -5px;
left: 0;
width: 20px;
height: 20px;
background-color: #007bff;
border-radius: 50%;
cursor: pointer;
}

.target-marker {
position: absolute;
top: -5px;
width: 2px;
height: 30px;
background-color: red;
z-index: 1;
}

.success {
color: green;
}

.error {
color: red;
}
</style>
<style scoped>
.captcha {
  cursor: pointer;
}
</style>